const Service = require('egg').Service;

class InfoService extends Service {
  async add() {
    const { ctx, app } = this;
    const { username, gender, birthday, age, address } = ctx.request.body;
    const data = await app.mysql.query(`insert into info (username, gender, age, birthday, address) values (?,?,?,?,?)`, [username, gender, age, birthday, address]);

    return { code: 0, msg: 'success', data: data.insertId }
  }
  async delete() {
    const { ctx, app } = this;
    const { id } = ctx.params;
    const data = await app.mysql.query(`delete from info where id = ${id}`);
    return { code: 0, msg: 'success', data: data.insertId }
  }
  async update() {
    const { ctx, app } = this;
    const { id } = ctx.params;
    const { username, gender, age, birthday, address, updateTime } = ctx.request.body;
    // update info set username=?, gender=?, age=?, birthday=?, address=?, updateTime=? where id=?
    const data = await app.mysql.query(`update info set username=?, gender=?, age=?, birthday=?, address=?, updateTime=? where id=?`, [username, gender, age, birthday, address, updateTime, id]);
    return { code: 0, msg: 'success', data }
  }
  async findAll() {
    const { ctx, app } = this;
    const data = await app.mysql.query(`select * from info`);
    return { code: 0, msg: 'success', data }
  }
  // page
  async page() {
    const { ctx, app } = this;
    const { page, size } = ctx.query;
    if (page && size) {
      console.log('sql: ---> ', page, size)
      const total = await app.mysql.query(`select count(id) as num from info`);
      const data = await app.mysql.query(`select * from info limit ${size} offset ${page * size}`);
      return { code: 0, msg: 'success', data, total: total[0].num }
    } else {
      const data = await app.mysql.query(`select * from info`);
      return { code: 0, msg: 'success', data }
    }
  }
  // moshu
  async search() {
    const { ctx, app } = this;
    const { keyword } = ctx.query;
    const data = await app.mysql.query(`select * from info where username like '%${keyword}%'`);
    return { code: 0, msg: 'success', data }
  }
  // 
  async deleteAll() {
    const { ctx, app } = this; // 1,2,3
    const data = await app.mysql.query(`delete from info where id in (?)`, [ctx.params.ids]);
    return { code: 0, msg: 'success', data }
  }
}

module.exports = InfoService